import { login, getUserInfo, GetUserInfoResDto } from '@/api/base'
import global from './global'
export interface UserDto {
    userId: string
    userName: string
    nickName: string
    phone: string
    sex: '0' | '1'
    avatar: string
    companyId: string
    isWaiting: boolean
    balance: number
}

class User {
    commission = {}
    openId = ''
    session_key = '' as string | undefined
    userId = 0
    userName = ''
    avatar = ''
    isWaiting = 1
    isSuper = false
    auditStatus = 0
    avatarUrl: '' | undefined
    sex: 0 | undefined
    phone = ''
    salesHeadUrl = ''
    role = 0
    waitLogin (): Promise<number> {
        return new Promise((resolve) => {
            const inter = setInterval(() => {
                if (!this.isWaiting) {
                    clearInterval(inter)
                    console.log(this.userId)
                    if (this.userId && this.auditStatus === 1) {
                        resolve(this.userId)
                    }
                }
            }, 300)
        })
      wx.showShareMenu({
        withShareTicket: true,
        /* //设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击 */
        menus: ["onShareAppMessage", "onShareTimeline"]
      })
    }

    async login () {
        console.log(this.userId, 'this.userId')
        if (this.userId) {
            console.log('user1')
            this.isWaiting = 0
            return Promise.resolve(this)
        }
        console.log('login2')
        // 未登录
        return this.reLogin()
    }

    async reLogin (): Promise<GetUserInfoResDto | undefined> {
        const codeResult = await uni.login({})
        console.log(codeResult, 'codeResult')
        const result = await login({
            code: ((codeResult as unknown) as { code: string }).code,
            appId: global.appId
        })

        console.log(result, 'resultresult')
        this.auditStatus = result.auditStatus
        this.openId = result.openid
        this.session_key = result.sessionKey
        if (!result.token) {
            this.isWaiting = 0
            return
            throw new Error()
        }
        global.token = result.token
        return this.getUserInfo()
    }

    async getUserInfo () {
        const result = await getUserInfo()
        this.commission = result
        this.isWaiting = 0
        this.userId = result.id
        this.phone = result.phone
        this.userName = result.salesName
        this.salesHeadUrl = result.salesHeadUrl
        this.role = result.role
        // this.avatar = result.avatar
        // this.isSuper = result.is_super
        return result
    }

    exit () {
        this.userId = 0
        this.userName = ''
        this.avatar = ''
        this.isSuper = false
    }
}

export default new User()
